import { Form, Modal } from 'antd';
import toast from 'react-hot-toast';
import { useCustomerState } from '../../stores/CustomerStore';
import CustomerInfoForm from '../CustomerInfoForm';

interface EditCustomerInfoModalProps {
  isOpen: boolean;
  onCancel: () => void;
}

function EditCustomerInfoModal({
  isOpen,
  onCancel,
}: EditCustomerInfoModalProps) {
  const { customer, setCustomer } = useCustomerState();
  const [form] = Form.useForm();

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const payload: any = {
        PID: values.PID,
        customerName: values.customerName,
        telephone: values.telephone,
        address: values.address,
      };
      if (values.password) {
        payload.password = values.password;
      }
      console.log(payload);
      const response = await fetch(
        `http://localhost:8000/customers/${customer?.customerID}`,
        {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        },
      );

      if (response.ok) {
        toast.success('操作成功');
        if (customer) {
          setCustomer({
            ...customer,
            PID: values.PID,
            customerName: values.customerName,
            telephone: values.telephone,
            address: values.address,
          });
        }
        onCancel();
      } else {
        const errorData = await response.json();
        toast.error(errorData.detail || '操作失败');
      }
    } catch (error) {
      // @ts-ignore
      toast.error(error.toString());
    }
  };

  return (
    <Modal
      title="修改客户信息"
      open={isOpen}
      onOk={handleOk}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form form={form} layout="vertical" initialValues={customer || {}}>
        <CustomerInfoForm isEditMode />
      </Form>
    </Modal>
  );
}

export default EditCustomerInfoModal;
